#ifndef _MESSAGEQUEUE_H
#define _MESSAGEQUEUE_H

#include <queue>
#include "zNullCmd.h"

//循环队列，便于多线程操作消息
typedef std::pair<unsigned int,unsigned char *> CmdPairType;
template <int QueueSize = 100*1024>
class MsgQueue
{
	public:
		MsgQueue()
		{
			queueRead = 0;
			queueWrite = 0;
		}
		~MsgQueue()
		{
			clear();
		}
		typedef std::pair<volatile bool , CmdPairType> CmdQueueType;
		CmdPairType *get()
		{
			CmdPairType *ret = NULL;
			if(cmdQueue[queueRead].first)
			{
				ret = &cmdQueue[queueRead].second;
			}
			return ret;
		}
		void erase()
		{
			delete [] (cmdQueue[queueRead].second.second);
			cmdQueue[queueRead].first = false;
			queueRead = (++queueRead)%QueueSize;
		}
		unsigned char * getMsgAddr()
		{
			return cmdQueue[queueRead].second.second;
		}
		bool put(const void *ptNullCmd,const unsigned int cmdLen)
		{
			unsigned char *buf = new unsigned char[cmdLen];
			if(buf)
			{
				bcopy(ptNullCmd,buf,cmdLen);
				if(!putQueueToArray() && !cmdQueue[queueWrite].first)
				{
					cmdQueue[queueWrite].second.first = cmdLen;
					cmdQueue[queueWrite].second.second = buf;
					cmdQueue[queueWrite].first = true;

					queueWrite = (++queueWrite)%QueueSize;
					return true;
				}
				else
				{
					queueCmd.push(std::make_pair(cmdLen,buf));
				}
				return true;
			}
			return false;
		}
	private:
		void clear()
		{
			while(putQueueToArray())
			{
				while(get())
				{
					erase();
				}
			}
			while(get())
			{
				erase();
			}
		}
		bool putQueueToArray()
		{
			bool left = false;
			while(!queueCmd.empty())
			{
				if(!cmdQueue[queueWrite].first)	
				{
					cmdQueue[queueWrite].second = queueCmd.front();
					cmdQueue[queueWrite].first = true;
					queueWrite = (++queueWrite)%QueueSize;
					queueCmd.pop();
				}
				else
				{
					left = true;
					break;
				}
			}
			return left;
		}
		CmdQueueType cmdQueue[QueueSize];
		std::queue<CmdPairType,std::deque<CmdPairType> > queueCmd;
		unsigned int queueWrite;
		unsigned int queueRead;
};

class MessageQueue
{
	
};

#endif
